using System;
using System.Collections.Generic;
using System.Linq;
using MyApp.WebApi.Entity;
using MyApp.WebApi.ParamModel;
using MyApp.WebApi.Repository;
using MyApp.WebApi.Utils;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;


namespace Admin3000.Backend.Controllers
{
    //商品列表
    // [Authorize]
    [ApiController]
    [Route("[controller]")]
    public class GoodsController : ControllerBase
    {
        private IRepository<Goods> _goodsRespository;
        private IRepository<Photos> _photosRespository;
        private IRepository<GoodsPhotos> _goodsPhotosRespository;
        private IRepository<Catagorys> _catagorysRespository;
        private IRepository<GoodsCatagorys> _goodsCatagorysRespository;
        private IRepository<Users> _usersRespository;
        private IRepository<UsersGoods> _usersGoodsRespository;
        private IRepository<OrdersSpecs> _orderSpecsRespository;
        private IRepository<GoodsSpecs> _goodsSpecsTypesRespository;
        private IRepository<Attributes> _attributesRespository;
        private IRepository<AttributeValues> _attributeValuesRespository;
        private IRepository<Comments> _commentsRespository;
        private IRepository<CommentTypes> _commentTypesRespository;
        private IRepository<Types> _typesRespository;
        private IRepository<GoodsAttributes> _goodsAttributesRespository;



        private TokenParameter _tokenParameter;
        private readonly IConfiguration _configuration;

        public GoodsController(
            IConfiguration configuration,
            IRepository<Goods> goodsRespository,
            IRepository<Photos> photosRespository,
            IRepository<GoodsPhotos> goodsPhotosRespository,
            IRepository<Catagorys> catagorysRespository,
            IRepository<GoodsCatagorys> goodsCatagorysRespository,
            IRepository<Users> usersRespository,
            IRepository<UsersGoods> usersGoodsRespository,
            IRepository<OrdersSpecs> orderSpecsRespository,
            IRepository<GoodsSpecs> goodsSpecsTypesRespository,
            IRepository<Attributes> attributesRespository,
            IRepository<AttributeValues> attributeValuesRespository,
            IRepository<Comments> commentsRespository,
            IRepository<CommentTypes> commentTypesRespository,
            IRepository<Types> typesRespository,
            IRepository<GoodsAttributes> goodsAttributesRespository
        )
        {
            _configuration = configuration;

            _goodsRespository = goodsRespository;
            _photosRespository = photosRespository;
            _goodsPhotosRespository = goodsPhotosRespository;
            _goodsCatagorysRespository = goodsCatagorysRespository;
            _catagorysRespository = catagorysRespository;
            _usersRespository = usersRespository;
            _usersGoodsRespository = usersGoodsRespository;
            _orderSpecsRespository = orderSpecsRespository;
            _goodsSpecsTypesRespository = goodsSpecsTypesRespository;
            _attributesRespository = attributesRespository;
            _attributeValuesRespository = attributeValuesRespository;
            _commentsRespository = commentsRespository;
            _commentTypesRespository = commentTypesRespository;
            _typesRespository = typesRespository;
            _goodsAttributesRespository = goodsAttributesRespository;

            _tokenParameter =
                _configuration
                    .GetSection("TokenParameter")
                    .Get<TokenParameter>();
        }


        //获取商品列表
        [HttpGet, Route("getlist")]
        public dynamic GetList()
        {
            // 获取所有满足条件的属性
            var list = from goodsphotos in _goodsPhotosRespository.Table
                       join goods in _goodsRespository.Table on goodsphotos.GoodsId equals goods.Id
                       join photos in _photosRespository.Table on goodsphotos.PhotosId equals photos.Id
                       join goodscatagorys in _goodsCatagorysRespository.Table on goods.Id equals goodscatagorys.GoodsId
                       join catagorys in _catagorysRespository.Table on goodscatagorys.CatagorysId equals catagorys.Id
                       join usersgoods in _usersGoodsRespository.Table on goods.Id equals usersgoods.GoodsId
                       join users in _usersRespository.Table on usersgoods.UsersId equals users.Id
                       join orderspecs in _orderSpecsRespository.Table on goods.Id equals orderspecs.GoodsId
                       join goodspecs in _goodsSpecsTypesRespository.Table on orderspecs.GoodsSpecsId equals goodspecs.Id
                       join attributes in _attributesRespository.Table on goodspecs.AttributesId equals attributes.Id
                       join attributevalues in _attributeValuesRespository.Table on goodspecs.AttributeValuesId equals attributevalues.Id

                       where goods.IsDeleted == false
                       select new
                       {
                           GoodsId = goods.Id,
                           PhotosId = photos.Id,
                           GoodsSpecsId = goodspecs.Id,
                           Username = users.Username,
                           GoodsName = goods.GoodsName,
                           Description = goods.Description,
                           GoodsCode = goods.GoodsCode,
                           Prices = goods.Prices,
                           CurrentPrices = goods.CurrentPrices,
                           Number = goods.Number,
                           Picture = photos.Picture,
                           CatagoryName = catagorys.CatagoryName,
                           ParentId = catagorys.ParentId,
                           AttributeName = attributes.AttributeName,
                           Values = attributevalues.Values
                       };

            var res = new
            {
                Code = 200,
                Data = list,
                Msg = "获取商品列表成功"
            };
            return JsonHelper.Serialize(res);
        }

        //商品表分页
        [HttpGet]
        public dynamic Get([FromQuery] Pager pager)

        {
            var pageIndex = pager.PageIndex;
            var pageSize = pager.PageSize;
            var rowsTotal = pager.RowsTotal;


            // 获得所有满足条件的记录
            var users =
                _goodsRespository.Table.Where(x => x.IsDeleted == false);



            // 对获得的记录分页
            var u =
                users.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            // 返回的数据里，带有数据和分页信息
            var res =
                new
                {
                    Code = 1000,
                    Data =
                        new
                        {
                            Data = u,
                            Pager =
                                new
                                {
                                    pageIndex,
                                    pageSize,
                                    rowsTotal = users.Count()
                                }
                        },
                    Msg = "获取商品列表成功^_^"
                };
            return res;
        }

        //获取商品表指定Id信息
        [HttpGet("{id}")]
        public dynamic Get(int id)
        {
            var AritpId = _goodsRespository.GetById(id);

            if (AritpId == null)
            {
                return new { Code = 1000, Data = "", Msg = "指定商品不存在" };
            }
            return new
            {
                Code = 1000,
                Data = AritpId,
                Msg = "获取商品列表成功^_^"
            };
        }

        //根据输入的字 模糊查找包含该字的所有商品列表和对应的商品信息
        [HttpGet, Route("search/{name}")]
        public dynamic GetGoodsName(string name)
        {
            // goodsRespository.Table.OrderByDescending(x=> x.GoodsName).Take(5);
            var goodsName = from goods in _goodsRespository.Table.Where(x => x.GoodsName.Contains(name))
                            join goodsPhotos in _goodsPhotosRespository.Table on goods.Id equals goodsPhotos.GoodsId
                            join photos in _photosRespository.Table on goodsPhotos.PhotosId equals photos.Id
                            where goods.IsDeleted == false
                            select new
                            {
                                GoodsId = goods.Id,
                                GoodsName = goods.GoodsName,
                                GoodsPrices = goods.Prices,
                                GoodsPicture = photos.Picture
                            };
            var res = new
            {
                Code = 200,
                Data = goodsName,
                Msg = "获取商品名称成功!"
            };
            return JsonHelper.Serialize(res);
        }


        //根据商品Id查找对应商品的信息
        [HttpGet, Route("goodsInfo/{id}")]
        public dynamic GetGoodsInfo(int id)
        {
            var list = _goodsRespository.Table.Where(x => x.Id == id).FirstOrDefault();
            var res = new
            {
                Code = 200,
                Data = list,
                Msg = "获取商品信息成功!"
            };
            return JsonHelper.Serialize(res);
        }

        //根据Id查找商品图片
        [HttpGet, Route("goodsPicture/{id}")]
        public dynamic GetGoodsPhotos(int id)
        {
            var list = from goodPhotos in _goodsPhotosRespository.Table
                       join goods in _goodsRespository.Table on goodPhotos.GoodsId equals goods.Id
                       join photos in _photosRespository.Table on goodPhotos.PhotosId equals photos.Id
                       where goods.Id == id
                       select new
                       {
                           GoodsId = goods.Id,
                           PhotosId = photos.Id,
                           Picture = photos.Picture

                       };
            var res = new
            {
                Code = 200,
                Data = list,
                Msg = "获取商品图片成功!"
            };
            return JsonHelper.Serialize(res);
        }
        [HttpGet, Route("goodsAttribute/{id}")]
        //根据Id查找商品属性和属性值  1
        public dynamic GetGoodsAttribute(int id)
        {
            var list = from goodsAttribute in _goodsAttributesRespository.Table
                       join goods in _goodsRespository.Table on goodsAttribute.GoodsId equals goods.Id
                       join attribute in _attributesRespository.Table on goodsAttribute.AttributesId equals attribute.Id
                       join attributeValues in _attributeValuesRespository.Table on goodsAttribute.AttributeValuesId equals attributeValues.Id
                       where goods.Id == id && goodsAttribute.AttributesId == 1
                       select new
                       {
                           GoodsId = goods.Id,
                           AttributeId = goodsAttribute.AttributesId,
                           Attribute = attribute.AttributeName,
                           AttributeValuesId = goodsAttribute.AttributeValuesId,
                           AttributeValues = attributeValues.Values
                       };


            var a = new List<object>();
            var b = new List<object>();
            foreach (var item in list)
            {

                b.Add(new { item.AttributeValues,item.AttributeValuesId });
                a.Add(new { item.Attribute,item.AttributeId, b = b });
            }
            var c = a.FirstOrDefault();


            var res = new
            {
                Code = 200,
                Data = c,
                Msg = "获取商品颜色值成功!"
            };
            return JsonHelper.Serialize(res);


            // var g = _goodsAttributesRespository.Table.ToList();


            // var list = g.Select(o =>
            // {

            //     var key = _attributesRespository.Table.Where(x => x.Id == o.AttributesId).FirstOrDefault();

            //     var value = _attributeValuesRespository.Table.ToList();

            //     var arr = new List<string>();

            //     foreach (var j in value)
            //     {
            //         if (j.Id == o.AttributeValuesId)
            //         {
            //             arr.Add(j.Values);
            //         }
            //     }

            //     return new
            //     {
            //         goodId = o.GoodsId,
            //         goodKey = key.AttributeName,
            //         goodValue = arr
            //     };
            // });


        }
        [HttpGet, Route("goodsAttributes/{id}")]
        //根据Id查找商品属性和属性值  2
        public dynamic GetGoodsAttributes(int id)
        {
            var list = from goodsAttribute in _goodsAttributesRespository.Table
                       join goods in _goodsRespository.Table on goodsAttribute.GoodsId equals goods.Id
                       join attribute in _attributesRespository.Table on goodsAttribute.AttributesId equals attribute.Id
                       join attributeValues in _attributeValuesRespository.Table on goodsAttribute.AttributeValuesId equals attributeValues.Id
                       where goods.Id == id && goodsAttribute.AttributesId == 2
                       select new
                       {
                           GoodsId = goods.Id,
                           AttributeId = goodsAttribute.AttributesId,
                           Attribute = attribute.AttributeName,
                           AttributeValuesId = goodsAttribute.AttributeValuesId,
                           AttributeValues = attributeValues.Values
                       };


            var a = new List<object>();
            var b = new List<object>();
            foreach (var item in list)
            {

                b.Add(new { item.AttributeValues,item.AttributeValuesId });
                a.Add(new { item.Attribute,item.AttributeId, b = b });
            }
            var c = a.FirstOrDefault();




            var res = new
            {
                Code = 200,
                Data = c,
                Msg = "获取商品尺寸和尺寸值成功!"
            };
            return JsonHelper.Serialize(res);


            // var g = _goodsAttributesRespository.Table.ToList();


            // var list = g.Select(o =>
            // {

            //     var key = _attributesRespository.Table.Where(x => x.Id == o.AttributesId).FirstOrDefault();

            //     var value = _attributeValuesRespository.Table.ToList();

            //     var arr = new List<string>();

            //     foreach (var j in value)
            //     {
            //         if (j.Id == o.AttributeValuesId)
            //         {
            //             arr.Add(j.Values);
            //         }
            //     }

            //     return new
            //     {
            //         goodId = o.GoodsId,
            //         goodKey = key.AttributeName,
            //         goodValue = arr
            //     };
            // });


        }



        //根据Id查找对应商品的用户评论详情
        [HttpGet, Route("goodsCommentDetail/{id}")]
        public dynamic GetCommentType(int id)
        {
            var list = from usersGoods in _usersGoodsRespository.Table
                       join users in _usersRespository.Table on usersGoods.UsersId equals users.Id
                       join goods in _goodsRespository.Table on usersGoods.GoodsId equals goods.Id
                       join comment in _commentsRespository.Table on usersGoods.CommentsId equals comment.Id
                       join commentType in _commentTypesRespository.Table on comment.Id equals commentType.CommentsId
                       join types in _typesRespository.Table on commentType.TypesId equals types.Id
                       where goods.Id == id
                       select new
                       {
                           GoodsId = goods.Id,
                           UsersId = users.Id,
                           CommentId = comment.Id,
                           UserName = users.Username,
                           Comment = comment.Comment,
                           CommentScore = comment.CommentScore,
                           CommentTypes = types.CommentType
                       };
            var res = new
            {
                Code = 200,
                Data = list,
                Msg = "获取商品的用户评论详情和成功!"
            };
            return JsonHelper.Serialize(res);
        }


        //根据Id返回好评率 (好评数量/总评论数)
        [HttpGet, Route("goodComment/{id}")]

        public dynamic GetGoodCommentRate(int id)
        {
            var list = from usersGoods in _usersGoodsRespository.Table
                       join users in _usersRespository.Table on usersGoods.UsersId equals users.Id
                       join goods in _goodsRespository.Table on usersGoods.GoodsId equals goods.Id
                       join comment in _commentsRespository.Table on usersGoods.CommentsId equals comment.Id
                       join commentType in _commentTypesRespository.Table on comment.Id equals commentType.CommentsId
                       join types in _typesRespository.Table on commentType.TypesId equals types.Id
                       where goods.Id == id
                       select new
                       {
                           //    评论类型Id为1 为好评 计算好评的数量
                           //    计算评论表的中总评论数
                           CommentsId = commentType.CommentsId,
                           TypeId = commentType.TypesId,


                       };
            var GoodComment = _commentTypesRespository.Table.Where(x => x.TypesId == 1).Count();
            var Comment = _commentsRespository.Table.ToList().Count();
            var GoodCommentRate = (GoodComment / Comment) * 100;
            var res = new
            {
                Code = 200,
                Data = new { list, GoodCommentRate },
                Msg = "获取商品的用户评论详情和成功!"
            };
            return JsonHelper.Serialize(res);
        }

        // 商品表添加
        [HttpPost]
        public string Post(NewGoods model)
        {
            // JsonSerializerSettings settings = new JsonSerializerSettings();
            // // settings.MissingMemberHandling = MissingMemberHandling.Ignore;
            // settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            var goodsname = model.GoodsName.Trim();
            var description = model.Description.Trim();
            var goodsCode = model.GoodsCode;
            var prices = model.Prices;
            var currentPrices = model.CurrentPrices;
            var number = model.Number;

            if (
                string.IsNullOrEmpty(goodsname)

            )
            {
                var tmp =
                    new
                    {
                        Code = 1004,
                        Data = "",
                        Msg = "商品不能为空，请确认后重试"
                    };
                return JsonHelper.Serialize(tmp);
            }

            var user =
                new Goods
                {
                    GoodsName = model.GoodsName.Trim(),
                    Description = model.Description.Trim(),
                    GoodsCode = model.GoodsCode,
                    Prices = model.Prices,
                    CurrentPrices = model.CurrentPrices,
                    Number = model.Number

                };

            _goodsRespository.Insert(user);

            var res = new { Code = 1000, Data = user, Msg = "添加商品成功" };
            return JsonHelper.Serialize(res);
        }
        // 商品表修改指定id
        [HttpPut("{id}")]
        public dynamic Put(int id, NewGoods model)
        {
            var GoodsId = _goodsRespository.GetById(id);

            if (GoodsId != null)
            {
                GoodsId.GoodsName = model.GoodsName;
                GoodsId.Description = model.Description;
                GoodsId.GoodsCode = model.GoodsCode;
                GoodsId.Prices = model.Prices;
                GoodsId.CurrentPrices = model.CurrentPrices;
                GoodsId.Number = model.Number;

                GoodsId.UpdatedTime = DateTime.Now;
                _goodsRespository.Update(GoodsId);
                return JsonHelper
                    .Serialize(new
                    {
                        Code = 1000,
                        Data = GoodsId,
                        Msg =
                            string
                                .Format("你修改商品的id为：{0}，已经修改成功，请注意查收",
                                id)
                    });
            }
            else
            {
                return JsonHelper
                    .Serialize(new
                    {
                        Code = 104,
                        Data = "",
                        Msg = "指定Id的商品不存在，请确认后重试"
                    });
            }
        }
        // 商品表删除
        [HttpDelete("{id}")]
        public dynamic Delete(int id)
        {
            var AritpId = _goodsRespository.GetById(id);
            if (AritpId != null)
            {
                _goodsRespository.Delete(id);
                return new
                {
                    Code = 1000,
                    Msg = string.Format("删除指定id为{0}的商品成功", id)
                };
            }
            else
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "指定Id的商品不存在，请确认后重试"
                };
            }
        }
    }
}
